<template>
  <!-- 转出运单 -->
  <div v-loading="loading" class="app-container">
    <!-- <mainTilte title="出运单基本信息" /> -->
    <div class="header_title_box">
      <h2>出运单基本信息</h2>
      <p class="main-style red">
        <el-select v-model="cabinetObj" filterable placeholder="请选择柜号" @change="changeCabinet">
          <el-option v-for="item of cabinetNoData" :key="item.id" :label="item.cabinet_no" :value="item.cabinet_no" />
        </el-select>
      </p>
    </div>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <!-- <el-col :span="8">
          <el-form-item label="出运单号" prop="code">
            <el-input v-model.trim="form.code" disabled />
          </el-form-item>
        </el-col> -->
        <el-col :span="8">
          <el-form-item label="运输方式" prop="shipment">
            <el-select v-model.trim="form.shipment" clearable placeholder="运输方式">
              <el-option v-for="(item, index) of issignContract" :key="index" :label="item.dict_data_name" :value="`${item.id}`" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="起运港" prop="shipment_port">
            <el-select v-model.trim="form.shipment_port" clearable placeholder="起运港">
              <el-option v-for="(item, index) of departureData" :key="index" :label="item.dict_data_name" :value="`${item.id}`" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="目的港" prop="destination_port">
            <el-select v-model.trim="form.destination_port" placeholder="目的港" clearable>
              <el-option v-for="(item, index) of destineData" :key="index" :label="item.dict_data_name" :value="`${item.id}`" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="拼柜类型" prop="lcl_type">
            <el-select v-model.trim="form.lcl_type" clearable placeholder="拼柜类型">
              <el-option v-for="(item, index) of cabinetData" :key="index" :label="item.dict_data_name" :value="`${item.id}`" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="柜号" prop="cabinet_no">
            <el-input v-model.trim="form.cabinet_no" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="柜型" prop="cabinet_type">
            <el-select v-model.trim="form.cabinet_type" clearable placeholder="柜型">
              <el-option v-for="(item, index) of cabinetList" :key="index" :label="item.dict_data_name" :value="`${item.id}`" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="封箱号" prop="seal_no">
            <el-input v-model.trim="form.seal_no" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="船名航次" prop="ships_name">
            <el-input v-model.trim="form.ships_name" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="货代" prop="lforwarder_company">
            <el-select v-model.trim="form.lforwarder_company" placeholder="货代" clearable>
              <el-option v-for="item of freightList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="装柜日期" prop="loading_date">
            <el-date-picker v-model="form.loading_date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="起运日期(ETD)" prop="shipment_date">
            <el-date-picker v-model="form.shipment_date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="预计到仓日期" prop="arrive_date">
            <el-date-picker v-model="form.arrive_date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="提单号" prop="bl_no">
            <el-input v-model.trim="form.bl_no" />
          </el-form-item>
        </el-col>
        <el-col :span="8" class="warehouse-tip">
          <el-form-item label="建议实体仓" prop="warehouse_id">
            <el-select v-model="form.warehouse_id">
              <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" :disabled="item.is_active === 0" />
            </el-select>
          </el-form-item>
          <p class="warehouse-tip-text">该实体仓只做预分仓的入仓参考，预分仓时以实际为准</p>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="notes">
            <el-input v-model="form.notes" type="textarea" autosize />
          </el-form-item>
        </el-col>
      </el-row>
      <mainTilte title="转运商品明细信息" />
      <el-table :data="form.products" stripe fit border class="mb24">
        <el-table-column fixed="left" label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" style="color: #ff4444" @click="del(scope.$index, 'products')">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="purchase_order_code" label="采购申请单号" width="180" align="center" />
        <el-table-column prop="contract_code" label="合同号" width="180" align="center" />
        <el-table-column prop="goods_code" label="系统sku" width="180" align="center" />
        <el-table-column label="转运数量" prop="trans_number" min-width="200" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'products.' + scope.$index + '.trans_number'" class="no-label mt22" :rules="numberRule">
              <el-input-number v-model="scope.row.trans_number" :precision="0" placeholder="请输入转运数量" :min="1" :max="scope.row.left_number" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="转运金额" width="180" align="center">
          <template slot-scope="scope">
            <p v-if="scope.row.trans_number">
              {{ $computed.accMul( scope.row.trans_number, scope.row.price) }}
            </p>
          </template>
        </el-table-column>
        <el-table-column label="未转运数量" prop="left_number" width="180" align="center" />
        <el-table-column prop="arrive_date" label="交货日期" width="180" align="center">
          <template slot-scope="scope">
            {{
              scope.row.arrive_date | formatDate("{y}-{m}-{d}")
            }}
          </template>
        </el-table-column>
        <el-table-column prop="goods_name" label="中文名称" width="180" align="center" />
        <el-table-column prop="goods_name_en" label="英文名称" width="180" align="center" />
        <el-table-column prop="container_rate" label="箱率" width="180" align="center" />
        <el-table-column prop="number" label="采购数量" width="180" align="center" />
        <el-table-column prop="notes" label="备注" width="200" align="center" />
      </el-table>
      <mainTilte title="转运配件明细信息" />
      <el-table :data="form.parts" stripe fit border>
        <el-table-column fixed="left" label="操作" width="100" align="center">
          <template slot-scope="scope">
            <el-button type="text" size="small" style="color: #ff4444" @click="del(scope.$index, 'parts')">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="purchase_order_code" label="采购申请单号" width="180" align="center" />
        <el-table-column prop="contract_code" label="合同号" width="180" align="center" />
        <el-table-column prop="goods_code" label="系统sku" width="180" align="center" />
        <el-table-column label="转运数量" prop="trans_number" min-width="200" align="center">
          <template slot-scope="scope">
            <el-form-item :prop="'parts.' + scope.$index + '.trans_number'" class="no-label mt22" :rules="numberRule">
              <el-input-number v-model="scope.row.trans_number" :precision="0" placeholder="请输入转运数量" :min="1" :max="scope.row.left_number" />
            </el-form-item>
          </template>
        </el-table-column>
        <el-table-column label="未转运数量" prop="left_number" width="180" align="center" />
        <el-table-column prop="arrive_date" label="交货日期" width="180" align="center">
          <template slot-scope="scope">
            {{
              scope.row.arrive_date | formatDate("{y}-{m}-{d}")
            }}
          </template>
        </el-table-column>
        <el-table-column prop="goods_name" label="中文名称" width="180" align="center" />
        <el-table-column prop="container_rate" label="箱率" width="180" align="center" />
        <el-table-column prop="number" label="采购数量" width="180" align="center" />
        <el-table-column prop="notes" label="备注" width="200" align="center" />
      </el-table>
      <el-form-item class="text-center">
        <el-button type="primary" :loading="btnLoading" @click="submit">确认生成</el-button>
        <el-button @click="cancel">取消生成</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { validChineseOrs } from '@/utils/validate'
// import cacheList from '@/layout/mixin/cacheList'
import { transhipmentAll } from '@/utils/publicData'
export default {
  name: 'OutWaybill',
  // mixins: [cacheList],
  data() {
    return {
      info: {}, // 详情
      cabinetObj: '',
      form: {
        purchase_contract_id: '', // 合同id
        shipment: null, // 运输方式
        shipment_port: null, // 起运港
        destination_port: null, // 目的港
        lcl_type: null, // 拼柜类型
        cabinet_no: null, // 柜号
        cabinet_type: null, // 柜型
        seal_no: null, // 封箱号
        ships_name: null, // 船名航次
        lforwarder_company: null, // 货代
        loading_date: null, // 装柜日期
        shipment_date: null, // 起运日期
        arrive_date: null, // 预计到仓日期
        bl_no: null, // 提单号
        warehouse_id: '', // 建议实体仓
        notes: null, // 备注
        products: [], // 商品
        parts: [] // 配件
      },
      rules: {
        // 运输方式
        shipment: [
          {
            required: true,
            message: '请选择运输方式',
            trigger: ['change', 'blur']
          }
        ],
        // 起运港
        shipment_port: [
          {
            required: true,
            message: '请选择起运港',
            trigger: ['change', 'blur']
          }
        ],
        // 目的港
        destination_port: [
          {
            required: true,
            message: '请选择目的港',
            trigger: ['change', 'blur']
          }
        ],
        // 拼柜类型
        lcl_type: [
          {
            required: true,
            message: '请选择拼柜类型',
            trigger: ['change', 'blur']
          }
        ],
        // 柜号
        cabinet_no: [
          { required: true, message: '请输入柜号', trigger: 'blur' },
          { max: 30, message: '柜号必须在30个字符以内', trigger: 'blur' }
        ],
        // 柜型
        cabinet_type: [
          {
            required: true,
            message: '请选择柜型',
            trigger: ['change', 'blur']
          }
        ],
        // 封箱号
        seal_no: [
          { required: true, message: '请输入封箱号', trigger: 'blur' },
          { max: 30, message: '封箱号必须在30个字符以内', trigger: 'blur' }
        ],
        // 船名班次
        ships_name: [
          { required: true, message: '请输入船名班次', trigger: 'blur' },
          { max: 150, message: '船名班次必须在150个字符以内', trigger: 'blur' }
        ],
        // 货代
        lforwarder_company: [
          {
            required: true,
            message: '请选择货代',
            trigger: ['change', 'blur']
          }
        ],
        // 装柜日期
        loading_date: [
          {
            required: true,
            message: '请选择装柜日期',
            trigger: ['change', 'blur']
          }
        ],
        // 起运日期
        shipment_date: [
          {
            required: true,
            message: '请选择起运日期',
            trigger: ['change', 'blur']
          }
        ],
        // 预计到仓日期
        arrive_date: [
          {
            required: true,
            message: '请选择预计到仓日期',
            trigger: ['change', 'blur']
          }
        ],
        // 提单号
        bl_no: [
          { required: true, message: '请输入提单号', trigger: 'blur' },
          { max: 30, message: '提单号必须在30个字符以内', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              if (validChineseOrs(value)) {
                callback(new Error('提单号须是字母，数字，非空字符组成'))
              } else {
                callback()
              }
            },
            trigger: 'change'
          }
        ],
        // 备注说明
        notes: [
          { max: 500, message: '备注说明必须在500个字符以内', trigger: 'blur' }
        ]
      },
      numberRule: [
        { required: true, message: '请输入销量', trigger: ['change', 'blur'] }
      ],
      issignContract: [],
      departureData: [],
      destineData: [],
      cabinetData: [],
      cabinetList: [],
      freightList: [],
      productIds: [],
      checkProductList: [],
      id: '',
      btnLoading: false,
      loading: false,
      warehouseList: [], // 实体仓列表
      cabinetNoData: []
    }
  },
  beforeDestroy() {
    window.localStorage.setItem('outWaybillData', JSON.stringify(this.form))
  },
  created() {
    const dataObj = window.localStorage.getItem('outWaybillData')
    if (dataObj) {
      this.form = JSON.parse(dataObj)
    }
    this.id = this.$route.params.id
    // this.getInfo()
    this.getFreightList() // 获取货代列表
    this.getDic() // 获取字典
    this.getWarehouseList() // 获取实体仓列表
    this.getInfo()
    transhipmentAll().then((data) => {
      this.cabinetNoData = data
    })
  },
  methods: {
    changeCabinet(value) {
      const dataObj = this.cabinetNoData.filter((item) => {
        return item.cabinet_no === value
      })[0]
      this.form.shipment = dataObj.shipment // 运输方式
      this.form.shipment_port = dataObj.shipment_port
      this.form.destination_port = dataObj.destination_port
      this.form.lcl_type = dataObj.lcl_type
      this.form.cabinet_no = dataObj.cabinet_no
      this.form.cabinet_type = dataObj.cabinet_type
      this.form.seal_no = dataObj.seal_no
      this.form.ships_name = dataObj.ships_name
      this.form.lforwarder_company = dataObj.lforwarder_company
      this.form.loading_date = dataObj.loading_date
      this.form.arrive_date = dataObj.arrive_date
      this.form.bl_no = dataObj.bl_no
      this.form.warehouse_id = dataObj.warehouse_id
      this.form.shipment_date = dataObj.shipment_date
    },
    // 获取 实体仓列表
    getWarehouseList() {
      const vm = this
      const params = {
        page: 1,
        limit: 10000,
        type: 1 // 1-实体仓 2-虚拟仓 3-残品仓 4-FBA仓
      }
      vm.$http.get('/warehouse', { params }).then(res => {
        vm.warehouseList = res.data
      })
    },
    // 获取 字典
    getDic() {
      const vm = this
      const dicParams = [{
        type: 'transport',
        key: 'issignContract',
        name: '运输方式'
      },
      {
        type: 'port',
        key: 'departureData',
        name: '起运港'
      },
      {
        type: 'destination',
        key: 'destineData',
        name: '目的港'
      },
      {
        type: 'load_type',
        key: 'cabinetData',
        name: '拼柜类型'
      },
      {
        type: 'cabinet_type',
        key: 'cabinetList',
        name: '柜型'
      }]
      const promiseArr = dicParams.map((e) => {
        return new Promise((resolve, reject) => {
          vm.$cache.getDic(e.type)
            .then((res) => {
              resolve({
                data: res,
                key: e.key
              })
            })
            .catch((err) => {
              reject(err)
            })
        })
      })
      Promise.all(promiseArr).then((res) => {
        res.forEach((e) => {
          vm[e.key] = e.data
        })
      })
    },
    // 获取货代列表
    getFreightList() {
      const vm = this
      const params = {
        page: 1,
        limit: 100000000,
        status: 1,
        type: 2
      }
      vm.$http.get('/lforwarder', { params }).then(res => {
        vm.freightList = res.data
      })
    },
    // 删除
    del(index, type) {
      const vm = this
      if (type === 'products') {
        vm.form.products.splice(index, 1)
      } else {
        vm.form.parts.splice(index, 1)
      }
    },
    // 获取商品列表
    getProducts() {
      const vm = this
      vm.$http
        .post('/purchase-contract/products', { ids: [this.id] })
        .then(res => {
          const { products, parts } = res.data
          vm.form.products = products.filter(e => e.left_number > 0).map(e => {
            e['trans_number'] = e.number
            e['contract_code'] = vm.info.code
            return e
          })
          vm.form.parts = parts.filter(e => e.left_number > 0).map(e => {
            e['trans_number'] = e.number
            e['contract_code'] = vm.info.code
            return e
          })
          vm.loading = false
        })
        .catch(() => {
          vm.loading = false
        })
    },
    // 生成出运单
    submit() {
      const vm = this
      const form = vm.$refs['form']
      form.validate(valid => {
        if (valid) {
          const length = vm.form.products.concat(vm.form.parts).length
          if (length <= 0) {
            return vm.$message.error('请至少转运一个商品')
          }
          vm.btnLoading = true
          const params = Object.assign({}, vm.form)
          params.products = params.products.concat(params.parts).map(e => {
            return {
              id: e.id,
              trans_number: e.trans_number
            }
          })
          delete params.parts
          vm.$http
            .post(`/transhipment-order`, params)
            .then(() => {
              vm.$message.success('生成出运单成功')
              vm.$http.get(`/purchase-contract?page=1&limit=10&audit_status=`).then(() => {
                vm.cancel()
                vm.btnLoading = false
              })
            })
            .catch(err => {
              console.log(err)
              vm.btnLoading = false
            })
        }
      })
    },
    // 取消
    cancel() {
      this.$router.push({ path: '/supplyChain/purchaseContract' })
    },
    // 获取详情
    getInfo() {
      const vm = this
      vm.loading = true
      vm.$http.get(`/purchase-contract/${vm.id}`).then(res => {
        vm.info = res.data
        vm.form.purchase_contract_id = vm.id
        vm.getProducts()
      })
    }
  }
}
</script>

<style scoped>
/deep/ .el-date-editor,
.el-select {
  width: 100%;
}
.text-center {
  text-align: center;
  margin-top: 20px;
}
.warehouse-tip {
  position: relative;
}
.warehouse-tip .warehouse-tip-text {
  position: absolute;
  bottom: 0;
  left: 120px;
  color: #ff4646;
  font-size: 12px;
  margin: 0;
}
</style>
